package com.mes.common.manager;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.mes.common.manager.iface.IBasicManager;
import com.mes.common.dao.iface.IBasicDao;
import com.mes.common.domain.BasicModel;

@Component
@Transactional(rollbackFor=Exception.class)
public class BasicManager<T> implements IBasicManager<T> {
	
	private final static Log log = LogFactory.getLog(BasicManager.class);
	
	protected IBasicDao<T> basicDao;
	
	public IBasicDao<T> getBasicDao() {
		return basicDao;
	}
	@Autowired
	public void setBasicDao(IBasicDao<T> basicDao) {
		this.basicDao = basicDao;
	}

	
	@Override
	public void add(T t) throws Exception {
		// TODO Auto-generated method stub
		basicDao.add(t);
	}

	@Override
	public void update(T t) throws Exception {
		// TODO Auto-generated method stub
		basicDao.update(t);
	}

	@Override
	public void delete(T t) throws Exception {
		// TODO Auto-generated method stub
		basicDao.delete(t);
	}
	
	@Override
	public void save(T t) throws Exception {
		// TODO Auto-generated method stub
		BasicModel basicModel = (BasicModel) t;
		if (basicModel.getObjectState() == BasicModel.OBJECTSTATE_TOBEADDED) {
			this.add(t);
		}else if (basicModel.getObjectState() == BasicModel.OBJECTSTATE_TOBEDELETED) {
			this.delete(t);
		}else if (basicModel.getObjectState() == BasicModel.OBJECTSTATE_TOBEUPDATED) {
			this.update(t);
		}
	}
	
	@Override
	public T getById(Serializable id) throws Exception {
		// TODO Auto-generated method stub
		return basicDao.getById(id);
	}
	
	@Override
	public void add(Collection<T> collection) throws Exception {
		for (T t : collection) {
			basicDao.add(t);
		};
	}
	
	@Override
	public void update(Collection<T> collection) throws Exception {
		for (T t : collection) {
			basicDao.update(t);
		};
	}
	
	@Override
	public void delete(Collection<T> collection) throws Exception {
		for (T t : collection) {
			basicDao.delete(t);
		};
	}
	
	public List<T> getByOutUid(String outUid) throws Exception {
		return basicDao.getByOutUid(outUid);
	}
	
	public T getSingleByOutUid(String outUid) throws Exception {
		return basicDao.getSingleByOutUid(outUid);
	}
	
}
